package com.xudow.app.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.task.PortraitUploadTask;
import com.xudow.app.ui.task.UserProfileTask;
import com.xudow.app.ui.user.AccountRelatedActivity;
import com.xudow.app.ui.user.AddressEditActivity;
import com.xudow.app.ui.user.BirthdayEditActivity;
import com.xudow.app.ui.user.CouponsActivity;
import com.xudow.app.ui.user.FavoriteActivity;
import com.xudow.app.ui.user.NicknameEditActivity;
import com.xudow.app.ui.user.OrdersActivity;
import com.xudow.app.ui.user.PhoneEditActivity;
import com.xudow.app.ui.user.QuestionsActivity;
import com.xudow.app.ui.user.UsernameEditActivity;
import com.xudow.app.util.AlbumUtil;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.StringUtils;
import com.xudow.app.util.TimeUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * User activity.
 *
 * @author lukecheng
 */
public class UserActivity extends BaseActivity {
    private static final String TAG = makeLogTag(UserActivity.class);

    private static final String TMP_PORTRAIT_PATH = "portrait.png";

    private static final int ALBUM_OK_KITKAT = 200;
    private static final int ALBUM_OK = 201;
    private static final int CROP_PHOTO = 202;
    private static final int CAMERA_OK = 203;

    private TextView nicknameTextView;  //昵称
    private TextView addressTextView;  //地址
    private TextView realnameTextView;  //真实名字
    private TextView cellphoneTextView;  //手机号码
    private TextView birthdayTextView;  //生日号码

    private String xuedouId = "";  //学兜ID

    private File tempFile;  //拍照获取图片临时文件

    /**
     * 头像上传Task
     */
    private PortraitUploadTask portraitUploadTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        nicknameTextView = (TextView) findViewById(R.id.nicknmae);
        addressTextView = (TextView) findViewById(R.id.address);
        realnameTextView = (TextView) findViewById(R.id.realname);
        cellphoneTextView = (TextView) findViewById(R.id.cellphone);
        birthdayTextView = (TextView) findViewById(R.id.birthday);

        XApplication application = (XApplication) getApplication();
        if (application.isStudent()) {
            findViewById(R.id.child_relate_item).setVisibility(View.GONE);
            findViewById(R.id.child_relate_item_border).setVisibility(View.GONE);
            findViewById(R.id.account_relate_item).setVisibility(View.GONE);
        }
    }

    @Override
    public boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        retrieveUserProfile();
    }

    /**
     * 获取用户基本信息
     */
    private void retrieveUserProfile() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UserProfileTask userProfileTask = new UserProfileTask(UserActivity.this,
                        userprofileHandler);
                userProfileTask.execute();
            }
        });
    }

    /**
     * 功能列表点击事件
     *
     * @param view
     */
    public void onFunctionListItemSelected(View view) {
        switch (view.getId()) {
            case R.id.orders_item: // 订单页面
                startActivity(new Intent(this, OrdersActivity.class));
                break;
            /*
            case R.id.kedoudou_item:
                startActivity(new Intent(this, ShoppingCartActivity.class));
                break;
            */
            case R.id.favorite_item: // 收藏页面
                startActivity(new Intent(this, FavoriteActivity.class));
                break;
            case R.id.coupons_item: // 优惠券
                startActivity(new Intent(this, CouponsActivity.class));
                break;
            case R.id.questions_item: // 我的提问
                startActivity(new Intent(this, QuestionsActivity.class));
                break;
            /*
            case R.id.activities_item:
                startActivity(new Intent(this, ActivitiesActivity.class));
                break;
            */
            case R.id.feedback_item: // 在线投诉
                startActivity(new Intent(this, FeedbackActivity.class));
                break;
            case R.id.security_item: // 账户与安全
                Intent sIntent = new Intent(this, SecurityActivity.class);
                sIntent.putExtra("xuedouId", xuedouId);
                startActivity(sIntent);
                break;
            case R.id.child_relate_item: // 关联孩子账号
                startActivity(new Intent(this, ChildRelateActivity.class));
                break;
            case R.id.account_relate_item: // 关联账户信息
                startActivity(new Intent(this, AccountRelatedActivity.class));
                break;
        }
    }

    /**
     * 返回按钮点击事件
     *
     * @param view
     */
    public void onBackBtnClick(View view) {
        finish();
    }

    /**
     * 头像点击事件
     *
     * @param view
     */
    public void onPortraitClick(View view) {
        final String[] options = {
                getString(R.string.from_camera),
                getString(R.string.from_album)
        };

        AlertDialog.Builder dlg = new AlertDialog.Builder(this);
        dlg.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (0 == which) {
                    takeImageFromCamera();
                } else {
                    takeImageFromAlbum();
                }
            }
        });
        dlg.create().show();
    }

    /**
     * 拍照获取图片
     */
    private void takeImageFromCamera() {
        if (!new File(Config.SDCARD_ROOT_DIR).exists()) {
            new File(Config.SDCARD_ROOT_DIR).mkdirs();
        }

        if (!new File(Config.SDCARD_ROOT_DIR + "/tmp/").exists()) {
            new File(Config.SDCARD_ROOT_DIR + "/tmp/").mkdirs();
        }

        String filename = System.currentTimeMillis() + ".png";
        tempFile = new File(Config.SDCARD_ROOT_DIR + "/tmp/" + filename);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("output", Uri.fromFile(tempFile));
        startActivityForResult(intent, CAMERA_OK);
    }

    /**
     * 从相册选择图片
     */
    private void takeImageFromAlbum() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            AlbumUtil.fromAlbum(this, ALBUM_OK_KITKAT);
        } else {
            AlbumUtil.fromAlbum(this, ALBUM_OK);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK != resultCode) {
            return;
        }

        Uri uri = null;

        switch (requestCode) {
            case ALBUM_OK:
                if (data != null) {
                    uri = data.getData();
                    cropPortrait(uri);
                }
                break;
            case ALBUM_OK_KITKAT:
                if (data != null) {
                    uri = Uri.parse(AlbumUtil.getPath(this, data.getData()));
                    cropPortrait(uri);
                }
                break;
            case CAMERA_OK:
                if (RESULT_OK == resultCode) {
                    cropPortrait(Uri.fromFile(tempFile));
                }
                break;
            case CROP_PHOTO:
                savePortrait(data);
                break;
        }
    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void cropPortrait(Uri uri) {
        if (null == uri) {
            return;
        }

        //4.4后gallery的最近和图片返回的content前缀的uri，需要将其转换为file:///
        //前缀的绝对地址，然后再去调用com.android.camera.action.CROP，将该uri给setData，就不会有权限问题了,
        //不然会提示 Can't load image

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            if (uri.toString().indexOf("file:///") != 0) {
                uri = Uri.parse("file:///" + uri.toString());
            }
        }

        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 72);
        intent.putExtra("outputY", 72);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, CROP_PHOTO);
    }

    /**
     * 保存头像
     *
     * @param data
     */
    public void savePortrait(Intent data) {
        String portraitPath = TMP_PORTRAIT_PATH;

        FileOutputStream portraitOutput = null;
        try {
            Bitmap portraitBmp = data.getParcelableExtra("data");
            portraitOutput = openFileOutput(portraitPath, Context.MODE_PRIVATE);
            portraitBmp.compress(Bitmap.CompressFormat.PNG, 100, portraitOutput);
        } catch (FileNotFoundException e) {
            LOGE(TAG, e.getMessage());
        } finally {
            if (null != portraitOutput) {
                try {
                    portraitOutput.close();
                } catch (IOException e) {
                    LOGE(TAG, e.getMessage());
                }
            }
        }

        showLodingDialog(getString(R.string.processing));

        String path = getFilesDir() + File.separator + portraitPath;

        portraitUploadTask = new PortraitUploadTask(this, portraitUploadHandler);
        portraitUploadTask.execute(path);
    }

    /**
     * 用户信息点击事件
     *
     * @param view
     */
    public void onUserInfoClcik(View view) {
        switch (view.getId()) {
            case R.id.username_item: // 真实姓名
                Intent intent = new Intent(this, UsernameEditActivity.class);
                intent.putExtra("username", realnameTextView.getText());
                startActivity(intent);
                break;
            case R.id.birthday_item: // 生日
                Intent birthdayIntent = new Intent(this, BirthdayEditActivity.class);
                birthdayIntent.putExtra("birthday", birthdayTextView.getText());
                startActivity(birthdayIntent);
                break;
            case R.id.mobile_item: // 手机号
                Intent phoneEditIntent = new Intent(this, PhoneEditActivity.class);
                phoneEditIntent.putExtra("phone", cellphoneTextView.getText());
                startActivity(phoneEditIntent);
                break;
            default:
                break;
        }
    }

    /**
     * 设置用户头像
     *
     * @param portraitUrl
     */
    private void setPortrait(String portraitUrl) {
        ImageView portrait = (ImageView) this.findViewById(R.id.portrait);

        String url = String.format("%s%s?name=%s", Config.BASE_URL, Config.IMAGE_LOAD_URL, portraitUrl);
        ImageUtils.loadImage(this, portrait, url, R.mipmap.def_portrait);
    }

    /**
     * 用户基本信息Handler
     */
    private Handler userprofileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UserProfileTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                UserDetailMessage ud = (UserDetailMessage) data.getSerializable("profile");
                UserProfileWithOther profile = ud.getUserDetail();

                if (StringUtils.isEmpty(profile.getNickName())) {
                    nicknameTextView.setText(getString(R.string.nickname_default_prompt));
                } else {
                    nicknameTextView.setText(profile.getNickName());
                }

                if (StringUtils.isEmpty(profile.getAddress())) {
                    addressTextView.setText(getString(R.string.address_default_prompt));
                } else {
                    addressTextView.setText(profile.getAddress());
                }

                realnameTextView.setText(profile.getName());
                cellphoneTextView.setText(profile.getMobilePhone());
                birthdayTextView.setText(TimeUtils.birthday(profile.getBirthday()));

                xuedouId = profile.getXuedouId();

                String portrait = profile.getPhotoPath();
                setPortrait(portrait);
            } else {
                //String message = msg.getData().getString("errMessage");
                //Toast.makeText(UserActivity.this, message, Toast.LENGTH_LONG).show();
            }
        }
    };

    /**
     * 删除临时头像
     */
    private void deleleTmpPortrait() {
        String path = getFilesDir() + File.separator + TMP_PORTRAIT_PATH;

        if (new File(path).exists()) {
            new File(path).delete();
        }
    }

    /**
     * 头像上传Handler
     */
    private Handler portraitUploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (PortraitUploadTask.SUCCESS == msg.what) {
                String message = getString(R.string.update_success);
                Toast.makeText(UserActivity.this, message, Toast.LENGTH_LONG).show();

                retrieveUserProfile();
                deleleTmpPortrait();
            } else {
                String message = getString(R.string.update_error);
                Toast.makeText(UserActivity.this, message, Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (null != portraitUploadTask && !portraitUploadTask.isCancelled()) {
                portraitUploadTask.cancel(true);
                portraitUploadTask = null;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 昵称点击事件
     *
     * @param view
     */
    public void onNicknameClick(View view) {
        String nickname = nicknameTextView.getText().toString();

        if (nickname.equals(getString(R.string.nickname_default_prompt))) {
            nickname = "";
        }

        Intent intent = new Intent(this, NicknameEditActivity.class);
        intent.putExtra("nickname", nickname);
        startActivity(intent);
    }

    /**
     * 地址点击事件
     *
     * @param view
     */
    public void onAddressClick(View view) {
        String address = addressTextView.getText().toString();

        if (address.equals(getString(R.string.address_default_prompt))) {
            address = "";
        }

        Intent intent = new Intent(this, AddressEditActivity.class);
        intent.putExtra("address", address);
        startActivity(intent);
    }
}
